package com.xyc.gulimall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import com.xyc.common.utils.PageUtils;
import com.xyc.common.utils.Query;
import com.xyc.gulimall.order.dao.OrderItemDao;
import com.xyc.gulimall.order.entity.OrderEntity;
import com.xyc.gulimall.order.entity.OrderItemEntity;
import com.xyc.gulimall.order.entity.OrderReturnReasonEntity;
import com.xyc.gulimall.order.service.OrderItemService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;

@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * queues:声明需要监听的所有队列
     * 参数：
     * 1、Message包含：消息头、消息体
     * 2、T<发送的消息的类型> OrderReturnReasonEntity content
     * 3、Channel channel 当前传输数据的通道
     * <p>
     * Queue可以有很多监听者，只要收到消息，队列删除消息，而且只能有一个收到此消息\
     * 场景：
     * 1）、订单服务启动多个；同一个消息，只能有一个客户端接收
     * 2）、只有一个消息完全处理完，方法运行结束，才可以接收下一个消息
     */
//    @RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage1(Message message,
                                OrderReturnReasonEntity content,
                                Channel channel) throws InterruptedException {
//        System.out.println("接收到消息：" + message);
//        Thread.sleep(3000);
        System.out.println("接收到OrderReturnReasonEntity消息：" + content);
        //channel内按顺序自增的。
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println("deliveryTag===>" + deliveryTag);

        //签收货物，非批量模式
        try {
            if (deliveryTag % 2 == 0) {
                //收货
                channel.basicAck(deliveryTag, false);
                System.out.println("签收了货物..." + deliveryTag);
            } else {
                //退货
                channel.basicNack(deliveryTag, false, false);//requeue:是否重新入队
//                channel.basicReject(deliveryTag,false);
                System.out.println("未签收货物..." + deliveryTag);
            }

        } catch (Exception e) {
            //网络中断
        }
    }

    @RabbitHandler
    public void receiveMessage2(OrderEntity content) throws InterruptedException {
        System.out.println("接收到OrderEntity消息：" + content);
    }

}